<template>
	<view class="the-page">
		<!-- 商品图片轮播 -->
		<swiper autoplay :interval="5000">
			<swiper-item v-for="(item ,index) in carouselList" :key="index">
				<image class="swiper-image" :src="baseUrl + item" mode="aspectFit"></image>
			</swiper-item>
		</swiper>

		<!-- 商品 明细 -->
		<uni-section title="商品信息" type="line" v-if="goods">
			<uni-list-item title="商品编号" :rightText="goods.id"></uni-list-item>
			<uni-list-item title="商品名称" :note="goods.name"></uni-list-item>
			<uni-list-item title="商品规格" :note="goods.spec"></uni-list-item>
			<uni-list-item title="单价" :rightText="goods.price"></uni-list-item>
			<uni-list-item title="库存数量" :rightText="goods.count"></uni-list-item>
			<uni-list-item title="上架时间" :rightText="goods.createTime"></uni-list-item>
			<uni-list-item title="详细描述"></uni-list-item>
			<view class="goods-content">
				<text v-html="goods.content"></text>
			</view>
		</uni-section>

		<!-- 商品购买区域 -->
		<view class="count-buy">
			<view class="buy-title">购买数量</view>
			<uni-number-box v-model="count" :min="1" :max="10" />
			<button type="primary" size="mini" @click="onClickAddShopcart">加入购物车</button>
		</view>

	</view>
</template>

<script>
	// 导入配置的基地址
	import {
		baseUrl
	} from "@/utils/config.js"
	
	//1.导入封装后的接口
	//根据id获取商品对象（详情）
	import * as goodsAPI from '@/api/goods.js';
	//导入将商品添加购物车接口
	import * as cartAPI from '@/api/cart.js';
	export default {
		data() {
			return {
				goods: null, //商品对象（详情）
				carouselList: [], //商品轮播图片数组
				count: 1 //步进器绑定的数量
			};
		},

		onLoad(options) {
			console.log(options);
			let id = options.goodsId;
			//2.使用封装后的接口
			goodsAPI.getDetailById(id).then(result => {
				console.log(result);
				this.goods = result.data; //保存API调用的返回数据
				//根据返回数据生成轮播图数组（用商品的中图片）
				
				// this.goods.album.forEach(item => {
				// 	this.carouselList.push(item);
				// }); //数据的遍历
				
				if (this.carouselList.length === 0) {
					this.carouselList.push(this.goods.img);
				}
			});
		},
		computed:{
				baseUrl(){
					return baseUrl
				}
		},

		// 方法
		methods: {
			//处理添加购物车
			onClickAddShopcart() {
				let params = {
					goodsId: this.goods.id,
					count: this.count
				};
				//2.使用封装后的接口,注意：接口有参数
				cartAPI.addCart(params)
					.then(result => {
						uni.showToast({ title: "添加成功" })
					})
					.catch(err => {
						console.log(err);
					});
			}
		},
	};
</script>

<style scoped lang="scss">
	.the-page {
		padding: 10px;
	}

	.swiper-image {
		width: 100%;
		height: 100%;
	}

	.goods-content {
		padding: 0 15px;
	}

	.count-buy {
		display: flex;
		flex-direction: row;
		margin: 20px 0px;
		align-items: center;
		justify-content: space-between;
		gap: 10px;

		.buy-title {
			padding-right: 10px;
			flex: 1;
		}
	}
</style>